<template>
    <div class="list-box">
        <div class="pannel-title pannel-between">
            <div>管理员列表</div>
            <a-button class="pannel-btn" size="small" type="primary" shape="round" @click="addAdmin()">
                <PlusCircleFilled />
                新增管理员
            </a-button>
        </div>
        <div class="line"></div>
        <div class="data-table">
            <a-table
                :columns="columns"
                :row-key="(record) => record.id"
                :data-source="dataSource"
                :pagination="pagination"
                :loading="isLoading"
                @change="handleTableChange"
            >
                <template #status="{text}">
                    <span class="span-green" v-if="text === 'Enabled'">已启用</span>
                    <span class="span-red" v-if="text === 'Disabled'">已禁用</span>
                </template>
                <template #action="{record}">
                    <a @click="editAdmin(record)" title="编辑" style="margin-right:5px;"><img src="@/assets/images/cz-edit.png"/></a>
                    <a @click="deleteAdmin(record)" title="删除"><img src="@/assets/images/cz-delete.png"/></a>
                </template>
            </a-table>
            <a-modal v-model:visible="visible" :maskClosable="false" :afterClose="closeModal">
                <h3 class="modal-title">{{ validate.form.id ? "修改" : "新增" }}</h3>
                <div class="modal-form">
                    <div class="modal-form-item">
                        <label class="required">用户名</label>
                        <div class="modal-input">
                            <a-input
                                v-model:value="validate.form.name"
                                :class="{ 'input-invalid': !validate.rules.name.$valid && validate.rules.name.$dirty }"
                                placeholder="请输入用户名"
                            />
                        </div>
                    </div>
                    <div class="modal-form-item">
                        <label class="required">联系人</label>
                        <div class="modal-input">
                            <a-input
                                v-model:value="validate.form.contactName"
                                :class="{ 'input-invalid': !validate.rules.contactName.$valid && validate.rules.name.$dirty }"
                                placeholder="请输入联系人"
                            />
                        </div>
                    </div>
                    <div class="modal-form-item">
                        <label class="required">联系人手机号</label>
                        <div class="modal-input">
                            <a-input
                                v-model:value="validate.form.contactMobile"
                                :class="{ 'input-invalid': !validate.rules.contactMobile.$valid && validate.rules.name.$dirty }"
                                placeholder="请输入联系手机"
                            />
                        </div>
                    </div>
                    <div class="modal-form-item">
                        <label class="required">登录账号</label>
                        <div class="modal-input">
                            <a-input
                                v-model:value="validate.form.loginId"
                                :class="{ 'input-invalid': !validate.rules.loginId.$valid && validate.rules.name.$dirty }"
                                placeholder="请输入登录账号"
                            />
                        </div>
                    </div>
                    <div class="modal-form-item">
                        <label v-if="validate.form.id">重置登录密码</label>
                        <label class="required" v-else>登录密码</label>
                        <div class="modal-input">
                            <a-input
                                v-model:value="validate.form.loginPw"
                                :class="{ 'input-invalid': !validate.rules.loginPw.$valid && validate.rules.name.$dirty }"
                                placeholder="请输入登录密码"
                            >
                                <template #suffix>
                                    <a-tooltip title="密码由6位以上数字、字母或者‘-’、‘_’、‘\’组成">
                                        <info-circle-outlined style="color: rgba(255, 0, 0, 0.7)" />
                                    </a-tooltip>
                                </template>
                            </a-input>
                        </div>
                    </div>
                    <div class="modal-form-item">
                        <label class="required">账号角色</label>
                        <div class="modal-input">
                            <a-select
                                v-model:value="validate.form.roleId"
                                style="width: 240px"
                                :class="{ 'input-invalid': !validate.rules.roleId.$valid && validate.rules.name.$dirty }"
                                :options="roleList"
                                placeholder="请选择角色"
                                @change="changeRole"
                            ></a-select>
                        </div>
                    </div>
                    <div class="modal-form-item">
                        <label class="required">岗位</label>
                        <div class="modal-input">
                            <a-select
                                v-model:value="validate.form.postId"
                                style="width: 240px"
                                :class="{ 'input-invalid': !validate.rules.postId.$valid && validate.rules.name.$dirty }"
                                :options="postList"
                                placeholder="请选择岗位"
                            ></a-select>
                        </div>
                    </div>
                    <div class="modal-form-item">
                        <label class="required">状态</label>
                        <div class="modal-input">
                            <a-select v-model:value="validate.form.status" style="width: 240px">
                                <a-select-option value="Enabled">启用</a-select-option>
                                <a-select-option value="Disabled">禁用</a-select-option>
                            </a-select>
                        </div>
                    </div>
                </div>
                <template #footer>
                    <div class="modal-btn">
                        <a-button type="default" shape="round" @click="cancel()">取消</a-button>
                        <a-button type="primary" shape="round" @click="confirm()">确定</a-button>
                    </div>
                </template>
            </a-modal>
        </div>
    </div>
</template>
<script>
import { PlusCircleFilled, InfoCircleOutlined } from "@ant-design/icons-vue";
import { useStore } from "vuex";
import { watch } from "vue";
import { reactive, ref } from "@vue/reactivity";
import { message, Table, Modal } from "ant-design-vue";
import httpRequest from "@/util/httpRequest";
import Validate from "@/util/validate";
export default {
    components: {
        PlusCircleFilled,
        InfoCircleOutlined,
        ATable: Table,
    },
    setup() {
        const store = useStore();
        //text：页面头部面包屑的显示文字，isBack：是否显示页面头部返回按钮
        store.dispatch("setBreadcrumb", {
            text: "系统设置 / 管理员管理",
            isBack: false,
        });
        const dataSource = ref([]);
        const validate = reactive(
            new Validate({
                id: [null],
                loginId: ["", [Validate.Required()]],
                roleId: ["", [Validate.Required()]],
                postId: ["", [Validate.Required()]],
                name: ["", [Validate.Required()]],
                status: ["Enabled", []],
                contactName: ["", [Validate.Required()]],
                contactMobile: ["", [Validate.Required(), Validate.Phone()]],
                loginPw: ["", [Validate.Required(), Validate.Pattern(/^[0-9A-Za-z_\\-]{6,32}$/)]],
            })
        );
        watch(
            () => validate.form.loginId,
            () => {
                validate.Validity("loginId");
            }
        );
        watch(
            () => validate.form.roleId,
            () => {
                validate.Validity("roleId");
            }
        );
        watch(
            () => validate.form.postId,
            () => {
                validate.Validity("postId");
            }
        );
        watch(
            () => validate.form.name,
            () => {
                validate.Validity("name");
            }
        );
        watch(
            () => validate.form.contactName,
            () => {
                validate.Validity("contactName");
            }
        );
        watch(
            () => validate.form.contactMobile,
            () => {
                validate.Validity("contactMobile");
            }
        );
        watch(
            () => validate.form.loginPw,
            () => {
                validate.Validity("loginPw");
            }
        );
        const columns = reactive([
            {
                title: "用户账号",
                dataIndex: "loginId",
                key: "loginId",
            },
            {
                title: "用户名",
                dataIndex: "name",
                key: "name",
            },
            {
                title: "联系人",
                dataIndex: "contactName",
                key: "contactName",
            },
            {
                title: "账号角色",
                dataIndex: "roleName",
                key: "roleName",
            },
            {
                title: "岗位",
                dataIndex: "postName",
                key: "postName",
            },
            {
                title: "联系电话",
                dataIndex: "contactMobile",
                key: "contactMobile",
            },
            {
                title: "创建日期",
                dataIndex: "createTime",
                key: "createTime",
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "status",
                slots: { customRender: "status" },
            },
            {
                title: "操作",
                key: "action",
                slots: { customRender: "action" },
            },
        ]);
        const filter = reactive({
            name: "",
            selected: "",
        });
        const pagination = reactive({
            current: 1,
            pageSize: 10,
            total: 0,
        });
        return {
            filter,
            dataSource,
            columns,
            pagination,
            isLoading: ref(false),
            visible: ref(false),
            validate,
        };
    },
    data() {
        return {
            roleList: [],
            postList: [],
            allPostList: [],
            closeModal: () => {
                this.validate.resetValue();
                this.$nextTick(() => {
                    this.validate.resetValid();
                });
            },
        };
    },
    mounted() {
        httpRequest.post("角色集合", {}).then((res) => {
            this.roleList = res.data.list.map((e) => {
                return { value: e.id, label: e.name };
            });
        });
        httpRequest.post("岗位集合", {}).then((res) => {
            this.postList = res.data.list.map((e) => {
                return { value: e.id, label: e.name,roleType:e.roleType };
            });
            this.allPostList = [...this.postList];
        });
        this.getList();
    },
    methods: {
        getList() {
            this.isLoading = true;
            httpRequest
                .post("管理员列表", { pageNo: this.pagination.current })
                .then((res) => {
                    this.dataSource = res.data.list;
                    this.pagination.total = res.data.pages * 10;
                })
                .finally(() => {
                    this.isLoading = false;
                });
        },
        handleTableChange(page) {
            this.pagination.current = page.current;
            this.getList();
        },
        deleteAdmin(item) {
            Modal.confirm({
                title: "系统提示",
                content: "确认删除当前管理员？",
                okText: "确认",
                cancelText: "取消",
                onOk: () => {
                    return new Promise((res) => {
                        httpRequest
                            .post("删除管理员", { loginId: item.loginId })
                            .then(() => {
                                message.warning("删除管理员成功！");
                                this.getList();
                            })
                            .catch(() => {
                                message.warning({ content: "管理员删除失败", key: "error" });
                            })
                            .finally(() => {
                                this.isLoading = false;
                                res();
                            });
                    });
                },
            });
        },
        editAdmin(item) {
            this.visible = true;
            this.validate.rules.loginPw.validates = [Validate.Pattern(/^[0-9A-Za-z_\\-]{6,32}$/)];
            this.validate.setValue(item);
        },
        cancel() {
            this.visible = false;
        },
        addAdmin() {
            this.validate.rules.loginPw.validates = [Validate.Required(), Validate.Pattern(/^[0-9A-Za-z_\\-]{6,32}$/)];
            this.visible = true;
        },
        confirm() {
            if (this.validate.UpdateValidate()) {
                const url = this.validate.form.id ? "编辑管理员" : "创建管理员";
                const msg = this.validate.form.id ? "修改成功" : "创建成功";
                httpRequest.post(url, this.validate.form).then(() => {
                    this.visible = false;
                    message.success(msg);
                });
            } else {
                console.log(this.validate.rules);
            }
        },
        changeRole(value) {
            if (value === 1) {
                this.postList = this.allPostList.filter((e) => {
                    return e.roleType === "SubBureau";
                });
                this.validate.setValue({ postId: null });
                this.validate.form.postId = null;
            } else {
                this.postList = this.allPostList.filter((e) => {
                    return e.roleType === "PoliceStation";
                });
                this.validate.setValue({ postId: null });
                this.validate.form.postId = null;
            }
            console.log(11,this.postList);
        },
    },
};
</script>
<style lang="less" scoped>
.line {
    width: 100%;
    margin: 20px 0;
    border-top: 1px solid #eee;
}
.span-green {
    display: flex;
    align-items: center;
    &:before {
        content: "";
        display: block;
        width: 4px;
        height: 4px;
        border-radius: 2px;
        margin-right: 5px;
        background: #14ce79;
    }
}
.span-red {
    display: flex;
    align-items: center;
    &:before {
        content: "";
        display: block;
        width: 4px;
        height: 4px;
        border-radius: 2px;
        margin-right: 5px;
        background: #fe4e50;
    }
}
</style>
